package com.llmoe.print.common.pdf;

import com.itextpdf.kernel.pdf.PdfReader;
import com.llmoe.print.common.SSL;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.text.PDFTextStripper;

import javax.imageio.ImageIO;
import javax.net.ssl.HttpsURLConnection;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import java.awt.image.BufferedImage;
import java.awt.print.PrinterJob;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 通过URL获得PDF内容 转存
 * @author sunyang
 * @date 2019/1/24 14:40
 */
public class PdfText2Url {

    /**
     * 传入一个.pdf 地址
     * @param pdfUrl 地址
     * @throws Exception
     */
    public static PDDocument readPdf(String pdfUrl) throws Exception {
        // 是否排序
        boolean sort = false;
        // 编码方式
        String encoding = "UTF-8";
        // 开始提取页数
        int startPage = 1;
        // 内存中存储的PDF Document
        PDDocument pdDocument = null;
        //输入流
        InputStream inputStream = null;
        PrintWriter out = null;
        BufferedReader in = null;
        try {
            try {
                // 当作一个URL来装载文件
//                pdfUrl = pdfUrl.replace("=","");
//                URL url = new URL(pdfUrl);
//                URLConnection con = url.openConnection();
//                con.setConnectTimeout(10 * 1000);
//                inputStream = con.getInputStream();
//                System.out.println(inputStream.toString());
//                pdDocument = PDDocument.load(inputStream);
                URL url = new URL(pdfUrl);
                HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
                httpUrlConn.setDoInput(true);
                httpUrlConn.setRequestMethod("GET");

                boolean addHttps = url.toString().startsWith("https");
                if (addHttps) {
                    SSL addSSL = new SSL();
                    addSSL.trustAllHosts((HttpsURLConnection) httpUrlConn);
                    ((HttpsURLConnection) httpUrlConn).setHostnameVerifier(addSSL.DO_NOT_VERIFY);
                    httpUrlConn.connect();
                } else {
                    httpUrlConn.connect();
                }
                inputStream = httpUrlConn.getInputStream();
                pdDocument = PDDocument.load(inputStream);
            } catch (MalformedURLException e) {
                System.out.println(e);
            }
            // 获取页码
            int endPage = pdDocument.getNumberOfPages();
            PDFTextStripper stripper = null;
            stripper = new PDFTextStripper();
            // 设置是否排序
            stripper.setSortByPosition(sort);
            // 设置起始页
            stripper.setStartPage(startPage);
            // 设置结束页
            stripper.setEndPage(endPage);
            //System.out.println(stripper.getText(pdDocument));
            System.out.println(" 输出成功！");

            try {
                    PDFRenderer renderer = new PDFRenderer(pdDocument);
                    /* dpi越大转换后越清晰，相对转换速度越慢 */
//                    PdfReader reader = new PdfReader("E:/imageSort");
                    int pages = pdDocument.getDocumentCatalog().getPages().getCount();
                    StringBuffer imgFilePath = null;
                    for (int i = 0; i < pages; i++) {
                        String imgFilePathPrefix = "D:\\out\\imageSort\\";
                        imgFilePath = new StringBuffer();
                        imgFilePath.append(imgFilePathPrefix);
                        Date dNow = new Date( );
                        SimpleDateFormat ft = new SimpleDateFormat ("yyyy\\MM\\dd\\");
                        imgFilePath.append(ft.format(dNow));
                        imgFilePath.append(System.currentTimeMillis()+".png");
                        File dstFile = new File(imgFilePath.toString());
                        BufferedImage image = renderer.renderImageWithDPI(i, 150);
                        //目录不存在则创建
                        isexitsPath("D:\\out\\imageSort\\"+ft.format(dNow)+"\\png");
                        ImageIO.write(image, "png", dstFile);
                    }
                    System.out.println("PDF文档转PNG图片成功！");
            } catch (IOException e) {
                e.printStackTrace();
            }
            PDFPrintable printable = new PDFPrintable(pdDocument, Scaling.ACTUAL_SIZE);
            PrinterJob job = PrinterJob.getPrinterJob();
            job.setPrintable(printable);
            PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();
            job.setPrintService(defaultPrintService);
            job.print();
            return pdDocument;
        } finally {
            if (inputStream != null) {
                // 关闭输出流
                inputStream.close();
            }
            if (pdDocument != null) {
                // 关闭PDF Document
                pdDocument.close();
            }
        }
    }

    public static boolean isexitsPath(String path)throws InterruptedException{
        String [] paths=path.split("\\\\");
        StringBuffer fullPath=new StringBuffer();
        for (int i = 0; i < paths.length; i++) {
            fullPath.append(paths[i]).append("\\\\");
            File file=new File(fullPath.toString());
            if(paths.length-1!=i){//判断path到文件名时，无须继续创建文件夹！
                if(!file.exists()){
                    file.mkdir();
                    System.out.println("创建目录为："+fullPath.toString());
                }
            }
        }
        File file=new File(fullPath.toString());//目录全路径
        if (!file.exists()) {
            return true;
        }else{
            return false;
        }
    }
}
